import type { Slide } from '@/types/slides'
import Http from './index'
import { ParseMarkdown, GeneratePPT } from './markdownToSlide'

const onlineCoursewareApi = {
  detailUrl: 'online_doc/',
  changeUrl: 'online_doc/',
}

/**
 * @name 获取在线PPT
 * @param id PPT的id
 */
export async function fetchGetOnlinePPT(id: number | string, tempId: string): Promise<FetchGetOnlinePPTResSchema | undefined> {
  const strId = String(id)
  const rs = await Http.Get<FetchOnlinePPTSchema>(onlineCoursewareApi.detailUrl + strId)
  
  if (rs && rs.items) {
    const { name, content, meta } = rs.items

    const parse = ParseMarkdown(meta)
    const pptList = await GeneratePPT(parse, tempId)

    try {
      // 有已经保存的内容
      const res = JSON.parse(content)

      if (res.tempId !== tempId) {
        throw Error('模板有变化，需更新')
      }
      
      return {
        title: name,
        tempId: res.tempId,
        slides: res.slides
      }
    }
    catch (err: any) {
      // 出错表示content为空或是不符合jsonStr规范
      const res: FetchGetOnlinePPTResSchema = {
        title: name,
        tempId: tempId,
        slides: pptList
      }
      
      return res
    }
  }
}

/**
 * @name 编辑在线PPT
 * @param id 要编辑的在线PPT的ID，可以是数字或字符串
 * @param data 包含要更新的在线PPT数据的对象
 * @returns 编辑成功返回更新后的在线PPT数据，否则返回false
 */
export async function fetchEditOnlinePPT(id: string, slides: Slide[], title: string, width: number, scale: number, tempId: string): Promise<boolean> {
  if (!id) return false

  const content: FetchGetOnlinePPTResSchema = {
    title,
    tempId,
    slides
  }

  const res: any = {
    id: id,
    content: JSON.stringify(content)
  }

  if (title) {
    res.name = title
  }

  const rs = await Http.Put(onlineCoursewareApi.detailUrl + id, res)
  if (rs && rs.items) {
    return true
  }
  return false
}

export async function fetchClearPPTMeta(id: string): Promise<boolean> {
  const rs = await Http.Put(onlineCoursewareApi.detailUrl + id, {
    id,
    content: ''
  })
  if (rs && rs.items) {
    return true
  }
  return false
}